import { useState, useCallback } from 'react';
import { get, post, del, getWithoutAuth, postWithoutAuth } from '@/utils/httpClient';

export interface MessageData {
  id: number;
  nickname: string;
  email?: string;
  content: string;
  status: number;
  statusDesc: string;
  reply?: string;
  replyTime?: string;
  replyUserName?: string;
  ipAddress?: string;
  isTop: number;
  likeCount: number;
  createTime: string;
  createTimeDisplay: string;
}

export interface MessageRequest {
  nickname: string;
  email?: string;
  content: string;
}

export interface MessagePageResult {
  records: MessageData[];
  total: number;
  current: number;
  size: number;
  pages: number;
}

export interface MessageStats {
  total: number;
  pending: number;
  approved: number;
  rejected: number;
}

export const useMessage = () => {
  const [messages, setMessages] = useState<MessageData[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [total, setTotal] = useState(0);
  const [submitting, setSubmitting] = useState(false);

  // 获取公开留言列表
  const getPublicMessages = useCallback(async (current: number = 1, size: number = 10) => {
    setLoading(true);
    setError(null);
    
    try {
      const url = `/api/message/public/list?current=${current}&size=${size}`;
      const result = await getWithoutAuth<MessagePageResult>(url);
      setMessages(result.records);
      setTotal(result.total);
    } catch (err: any) {
      setError(err || '获取留言失败');
    } finally {
      setLoading(false);
    }
  }, []);

  // 提交留言
  const submitMessage = useCallback(async (messageData: MessageRequest) => {
    setSubmitting(true);
    setError(null);
    
    try {
      const result = await postWithoutAuth<number>('/api/message/submit', messageData);
      return result;
    } catch (err: any) {
      setError(err || '提交留言失败');
      throw err;
    } finally {
      setSubmitting(false);
    }
  }, []);

  // 点赞留言
  const likeMessage = useCallback(async (messageId: number) => {
    try {
      const result = await postWithoutAuth<number>(`/api/message/${messageId}/like`, {});
      
      // 更新本地状态
      setMessages(prev => prev.map(msg => 
        msg.id === messageId 
          ? { ...msg, likeCount: result }
          : msg
      ));
      return result;
    } catch (err: any) {
      setError(err || '点赞失败');
      throw err;
    }
  }, []);

  // 管理员获取留言列表
  const getAdminMessages = useCallback(async (
    current: number = 1, 
    size: number = 10, 
    status?: number, 
    keyword?: string
  ) => {
    setLoading(true);
    setError(null);
    
    try {
      let url = `/api/message/admin/list?current=${current}&size=${size}`;
      if (status !== undefined) url += `&status=${status}`;
      if (keyword) url += `&keyword=${encodeURIComponent(keyword)}`;
      
      const result = await get<MessagePageResult>(url);
      setMessages(result.records);
      setTotal(result.total);
    } catch (err: any) {
      setError(err || '获取留言失败');
    } finally {
      setLoading(false);
    }
  }, []);

  // 审核留言
  const auditMessage = useCallback(async (
    messageId: number, 
    status: number, 
    reply?: string
  ) => {
    try {
      let url = `/api/message/admin/${messageId}/audit?status=${status}`;
      if (reply) url += `&reply=${encodeURIComponent(reply)}`;
      
      const result = await post<boolean>(url, {});
      return result;
    } catch (err: any) {
      setError(err || '审核失败');
      throw err;
    }
  }, []);

  // 删除留言
  const deleteMessage = useCallback(async (messageId: number) => {
    try {
      const result = await del<boolean>(`/api/message/admin/${messageId}`);
      
      // 从本地状态中移除
      setMessages(prev => prev.filter(msg => msg.id !== messageId));
      return result;
    } catch (err: any) {
      setError(err || '删除失败');
      throw err;
    }
  }, []);

  // 置顶留言
  const topMessage = useCallback(async (messageId: number, isTop: number) => {
    try {
      const result = await post<boolean>(`/api/message/admin/${messageId}/top?isTop=${isTop}`, {});
      
      // 更新本地状态
      setMessages(prev => prev.map(msg => 
        msg.id === messageId 
          ? { ...msg, isTop }
          : msg
      ));
      return result;
    } catch (err: any) {
      setError(err || '操作失败');
      throw err;
    }
  }, []);

  // 获取留言统计
  const getMessageStats = useCallback(async () => {
    try {
      const result = await get<MessageStats>('/api/message/admin/stats');
      return result;
    } catch (err: any) {
      setError(err || '获取统计失败');
      throw err;
    }
  }, []);

  // 清除错误
  const clearError = useCallback(() => {
    setError(null);
  }, []);

  return {
    messages,
    loading,
    error,
    total,
    submitting,
    getPublicMessages,
    submitMessage,
    likeMessage,
    getAdminMessages,
    auditMessage,
    deleteMessage,
    topMessage,
    getMessageStats,
    clearError
  };
};